package handler

import (
	"github.com/gin-gonic/gin"
	"github.com/mangenotwork/common/conf"
	"github.com/mangenotwork/common/ginHelper"
	"github.com/mangenotwork/common/log"
	"github.com/mangenotwork/common/utils"
	"net/http"
	"time"
)

func ginH(h gin.H) gin.H {
	h["Title"] = "写了两年半的博客"
	h["TimeStamp"] = time.Now().Unix()
	return h
}

func NotFond(c *gin.Context) {
	c.HTML(
		http.StatusOK,
		"notfond.html",
		ginH(gin.H{}),
	)
}

func LoginPage(c *gin.Context) {
	token, err := c.Cookie("sing")
	if err != nil {
		log.Info("err", err)
		goto LoginPage
	}

	log.Info("token", token)

	if token != "" {
		j := utils.NewJWT(conf.Conf.Default.Jwt.Secret, conf.Conf.Default.Jwt.Expire)
		if err := j.ParseToken(token); err == nil {
			c.Redirect(http.StatusFound, "/home")
			return
		}
	}

LoginPage:

	c.HTML(
		http.StatusOK,
		"login.html",
		ginH(gin.H{
			"csrf": ginHelper.FormSetCSRF(c.Request),
		}),
	)

	return
}

func DownLoad(c *gin.Context) {
	c.HTML(
		http.StatusOK,
		"download.html",
		gin.H{
			"Title":     "下载",
			"TimeStamp": time.Now().Unix(),
		},
	)
}

func IosPage(c *gin.Context) {

	visitor, _ := c.Cookie("visitor")
	if len(visitor) == 0 {
		visitor = utils.IDMd5()
	}

	c.SetCookie("visitor", visitor, 1864000, "/", "", false, true)

	c.HTML(
		http.StatusOK,
		"ios_download.html",
		gin.H{
			"Title":     "下载",
			"TimeStamp": time.Now().Unix(),
		},
	)
}

func HomePage(c *gin.Context) {
	c.HTML(
		http.StatusOK,
		"home.html",
		ginH(gin.H{
			"nav": "home",
		}),
	)
}

func UserPage(c *gin.Context) {
	c.HTML(
		http.StatusOK,
		"user.html",
		ginH(gin.H{
			"nav": "user",
		}),
	)
}

func RoomPage(c *gin.Context) {
	c.HTML(
		http.StatusOK,
		"room.html",
		ginH(gin.H{
			"nav": "room",
		}),
	)
}

func ConfPage(c *gin.Context) {

	apiUrl, _ := conf.YamlGetString("apiUrl")

	c.HTML(
		http.StatusOK,
		"conf.html",
		ginH(gin.H{
			"nav":      "conf",
			"download": apiUrl + "/download/app.apk",
		}),
	)
}

func IosUUIDPage(c *gin.Context) {
	c.HTML(
		http.StatusOK,
		"ios_uuid.html",
		ginH(gin.H{
			"nav": "ios",
		}),
	)
}
